#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using Neatly.Load.Manager;
using Neatly.UI;
using UnityEngine;

namespace Neatly.Module
{
    public class AtlasModule : ModuleSingleton<AtlasModule>
    {
        private readonly Dictionary<string, Vector4> m_Padding = new();
        private readonly Dictionary<string, string> m_AtlasConfig = new();
        private string[] m_EmojiDirect;

        public override async UniTask Init()
        {
            m_Padding.Clear();
            m_AtlasConfig.Clear();
            var atlasConfig = await AtlasLoadManager.Instance.LoadAtlasConfig();
            foreach (var atlasItem in atlasConfig.atlasList)
            {
                var itemList = atlasItem.paddingList;
                bool isEmoji = atlasItem.name == NeatlyConfig.NAME_EMOJI_LIBRARY;
                if (isEmoji)
                {
                    m_EmojiDirect = new string[itemList.Count];
                }
                for (int j = 0; j < itemList.Count; j++)
                {
                    string spriteName = itemList[j].name;
                    if (m_AtlasConfig.ContainsKey(spriteName))
                    {
                        m_Padding[spriteName] = itemList[j].padding;
                        m_AtlasConfig[spriteName] = atlasItem.name;
#if UNITY_EDITOR
                        NDebug.LogError($"AtlasModule Sprite重复:{spriteName}");
#endif
                    }
                    else
                    {
                        m_Padding.Add(spriteName, itemList[j].padding);
                        m_AtlasConfig.Add(spriteName, atlasItem.name);
                    }
                    if (isEmoji)
                    {
                        m_EmojiDirect[j] = itemList[j].name;
                    }
                }
            }
        }

        public string[] GetEmojiLibrary()
        {
            return m_EmojiDirect;
        }

        public void AddRef(ImageInterface image)
        {
            string spriteName = image.GetSpriteName();
            if (string.IsNullOrEmpty(spriteName) || !NeatlyConfig.AssetBundleEnable || !Application.isPlaying) return;
            try
            {
                LoadModule.Instance.AddAtlasRef(m_AtlasConfig[spriteName]);
            }
            catch (Exception)
            {
                // NDebug.LogError("SpriteName错误:{0}", spriteName);
            }
        }

        public void LoseRef(ImageInterface image)
        {
            string spriteName = image.GetSpriteName();
            if (string.IsNullOrEmpty(spriteName) || !NeatlyConfig.AssetBundleEnable || !Application.isPlaying) return;
            if (m_AtlasConfig.TryGetValue(spriteName, out var atlasName))
            {
                LoadModule.Instance.LoseAtlasRef(atlasName);
            }
        }

        public async void SetSprite(ImageInterface image, string spriteName)
        {
            if (m_AtlasConfig.TryGetValue(spriteName, out var atlasName))
            {
                LoseRef(image);
                var atlasInfo = await LoadModule.Instance.LoadAtlasInfo(atlasName);
                image.SetSprite(spriteName, atlasInfo.GetSprite(spriteName), atlasInfo.material);
            }
            else
            {
                NDebug.LogWarning("找不到 SpriteName错误:{0}", spriteName);
            }
        }

        public async UniTask<(Sprite[], Material[])> LoadSpriteList(string[] spriteNameArray)
        {
            Sprite[] spriteArray = new Sprite[spriteNameArray.Length];
            var materialArray = new Material[spriteNameArray.Length];
            for (int i = 0; i < spriteArray.Length; i++)
            {
                var index = i;
                var atlasInfo = await LoadModule.Instance.LoadAtlasInfo(m_AtlasConfig[spriteNameArray[i]]);
                spriteArray[index] = atlasInfo.GetSprite(spriteNameArray[index]);
                materialArray[index] = atlasInfo.material;
            }
            return (spriteArray, materialArray);
        }

        public Dictionary<string, Vector4> GetUIPadding()
        {
            return m_Padding;
        }
    }
}